package com.tnl.app.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.tnl.base.SystemConfig;
import com.tnl.base.web.JsonController;

@Controller
@RequestMapping("/oauth")
public class WebOauthController extends JsonController {

	private static final Logger logger = LoggerFactory.getLogger(WebOauthController.class);

	 
	/**
	 * PC扫码登陆回调 获取AccessToken以及用户信息跟微信公众号授权用户用户信息一样
	 */
	@RequestMapping(value = "/webCallBack")
	public void webCallBack(HttpServletResponse response,HttpServletRequest req) {
		// 用户同意授权，获取code
		String code = req.getParameter("code");
		String state =req.getParameter("state");
		if (code != null) {
			System.out.println("code>" + code + " state>" + state);
			String appId = SystemConfig.getProperties("webAppId");
			String secret = SystemConfig.getProperties("webAppSecret");
			// 通过code换取网页授权access_token
			SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
			String json = snsAccessToken.getJson();
			System.out.println("通过code获取access_token>>" + json);
			String token = snsAccessToken.getAccessToken();
			String openId = snsAccessToken.getOpenid();
			// 拉取用户信息(需scope为 snsapi_userinfo)
			ApiResult apiResult = SnsApi.getUserInfo(token, openId);

			logger.warn("getUserInfo:" + apiResult.getJson());
			if (apiResult.isSucceed()) {
				JSONObject jsonObject = JSON.parseObject(apiResult.getJson());
				String nickName = jsonObject.getString("nickname");
				// 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
				int sex = jsonObject.getIntValue("sex");
				String city = jsonObject.getString("city");// 城市
				String province = jsonObject.getString("province");// 省份
				String country = jsonObject.getString("country");// 国家
				String headimgurl = jsonObject.getString("headimgurl");
				String unionid = jsonObject.getString("unionid");
			}
			this.successJson(apiResult.getJson(), "通过code获取access_token>>", response);
		}

	}


}
